import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cartList: [],
  },
  mutations: {
    // eslint-disable-next-line no-unused-vars
    addCounter(state, info) {
      // 这样修改是追踪的
      info.count++
    },
    addToCart(state, info) {
      info.count = 1
      info.checked = true
      state.cartList.push(info)
    },
    addcart(state, info) {
      console.log('+')
      state.cartList.find(item => item.iid == info.iid).count  = state.cartList.find(item => item.iid == info.iid).count + 1
    },
    subcart(state, info) {
      console.log('-');
      state.cartList.find(item => item.iid == info.iid).count  = state.cartList.find(item => item.iid == info.iid).count - 1
    }
  },
  actions: {
    addCart(context, info) {
      // eslint-disable-next-line no-unused-vars
      return new Promise((resolve, reject) => {
        // 判断之前商品是不是之前添加过 使用数组的find方法
        let oldProduct = context.state.cartList.find(item => item.iid === info.iid)
        if (oldProduct) {
          context.commit('addCounter', oldProduct)
          resolve('商品数量+1')
        } else {
          context.commit('addToCart', info)
          resolve('添加新商品')
        }
      })
    }
  },
  getters: {
    cartLength(state) {
      return state.cartList.length
    },
    getcartList(state) {
      return state.cartList
    }
  }
})
